package com.fuershiye.woman.monitor.dao;

import java.math.BigInteger;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.fuershiye.woman.monitor.beans.Page;
import com.fuershiye.woman.monitor.model.Bulletin;
import com.fuershiye.woman.monitor.utils.DaoSqlUtil;

@Repository("bulletinDao")
@SuppressWarnings("unchecked")
public class BulletinDao {

    @Autowired
    private HibernateDao hibernateDao;

    public void save(Bulletin bulletin){
        hibernateDao.save(bulletin);
    }

    public Bulletin get(Long id) {
        return hibernateDao.getById(Bulletin.class,id);
    }

    public void delete(Long id) {
        String sql = "update Bulletin set status = 0 where id = ?";
        SQLQuery query = hibernateDao.getSqlQuery(sql).addEntity(Bulletin.class);
        query.setLong(0, id);
        query.executeUpdate();
    }
    
    @SuppressWarnings("unchecked")
	public List<Bulletin> listByCondition(String title, Integer type, Integer status, Page page) {
    	
		StringBuffer sb = new StringBuffer("from Bulletin where 1=1 ");
		if (StringUtils.isNotBlank(title)) {
			sb.append("and title like:title ");
		}
		sb = DaoSqlUtil.appendSql(sb, "type", type);
		sb = DaoSqlUtil.appendSql(sb, "status", status);
		sb.append("ORDER BY mtime DESC");
		
		Query query = hibernateDao.getQuery(sb.toString());
		if (StringUtils.isNotBlank(title)) {
			query.setString("title", "%" + title + "%");
		}
		query = DaoSqlUtil.appendQuery(query, "type", type);
		query = DaoSqlUtil.appendQuery(query, "status", status);
		
		query.setFirstResult(page.getStart());
		query.setMaxResults(page.getPageSize()); 
		
		return query.list();
	}
    
    public int countByCondition(String title, Integer type, Integer status) {
    	
		StringBuffer sb = new StringBuffer("select count(*) from bulletin r where 1=1 ");
		
    	if (StringUtils.isNotBlank(title)) {
    		sb.append("and title like:title ");
    	}
    	sb = DaoSqlUtil.appendSql(sb, "type", type);
    	sb = DaoSqlUtil.appendSql(sb, "status", status);
    	sb.append("ORDER BY mtime DESC");
    	
    	Query query = hibernateDao.getSqlQuery(sb.toString());
    	if (StringUtils.isNotBlank(title)) {
    		query.setString("title", "%" + title + "%");
    	}
    	query = DaoSqlUtil.appendQuery(query, "type", type);
    	query = DaoSqlUtil.appendQuery(query, "status", status);

		BigInteger count = (BigInteger) query.uniqueResult();
		return (int) count.longValue();
    }
	
}
